package com.wwj.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wwj.reggie.common.R;
import com.wwj.reggie.dto.SetmealDto;
import com.wwj.reggie.entity.Category;
import com.wwj.reggie.entity.Dish;
import com.wwj.reggie.entity.Setmeal;
import com.wwj.reggie.service.CategoryService;
import com.wwj.reggie.service.SetmealDishService;
import com.wwj.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> saveSetmeal(@RequestBody SetmealDto setmealDto){
        log.info(setmealDto.toString());

        setmealService.saveWithDish(setmealDto);

        return R.success("");
    }

    /**
     * 套餐分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        //条件构造器对象
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper();
        //添加过滤条件
        lqw.like(name != null, Setmeal::getName, name)
                .eq(Setmeal::getIsDeleted, 0);
        //添加排序条件
        lqw.orderByDesc(Setmeal::getUpdateTime);

        //执行查询
        setmealService.page(pageInfo, lqw);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, setmealDtoPage, "records");

        //将pageInfo中的records取出
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> setmealDtos = records.stream().map((item) -> { //遍历集合中的Setmeal对象
            SetmealDto setmealDto = new SetmealDto();

            BeanUtils.copyProperties(item, setmealDto);

            Category category = categoryService.getById(item.getCategoryId()); //在数据库中查找对应分类id的数据，封装成分类对象
            String categoryName = category.getName(); //取出分类对象中的分类名称
            setmealDto.setCategoryName(categoryName);

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(setmealDtos);

        return R.success(setmealDtoPage);
    }


/**
     * 删除套餐（逻辑删除）
     * @param ids
     * @return
     */
/*
    @DeleteMapping
    public R<String> deleteSetmeal(@RequestParam List<Long> ids){

        List<Setmeal> list = ids.stream().map((item) -> {
            Setmeal setmeal = setmealService.getById(item);
            setmeal.setIsDeleted(1);
            return setmeal;
        }).collect(Collectors.toList());

        setmealService.updateBatchById(list);

        return  R.success("");
    }
*/

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> deleteSetmeal(@RequestParam List<Long> ids){
        setmealService.removeWithDish(ids);
        return R.success("");
    }

    /**
     * 套餐状态：修改————批量修改
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> statusUpdate(@PathVariable int status , String[] ids){

        List<Setmeal> Setmeals = new ArrayList<>();

        for (String id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(status);
            Setmeals.add(setmeal);
        }

        setmealService.updateBatchById(Setmeals);

        return R.success("");
    }

    /**
     * 根据id查询套餐及其菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);

        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> setmealUpdate(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithDish(setmealDto);
        return R.success("");
    }

    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId())
           .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        lqw.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> setmealList = setmealService.list(lqw);

        return R.success(setmealList);
    }

}
